<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use App\Models\User;

class AuthController extends Controller
{
    /**
     * 用户注册
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        try {
            $request->validate([
                'user_type' => 'required|in:user,admin',
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users',
                'password' => 'required|string|min:6|confirmed',
            ]);

            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'user_type' => $request->user_type, // 'user' 或 'admin'
            ]);

            // 创建令牌
            $token = $user->createToken('auth-token')->plainTextToken;

            return response()->json([
                'success' => true,
                'message' => $request->user_type === 'admin' ? '管理员注册成功，请等待审核' : '注册成功',
                'data' => [
                    'user' => $user,
                    'token' => $token
                ]
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '注册失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 用户登录
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        try {
            $request->validate([
                'user_type' => 'required|in:user,admin',
                'email' => 'required|email',
                'password' => 'required',
            ]);

            $user = User::where('email', $request->email)->first();

            // 检查用户是否存在
            if (!$user || !Hash::check($request->password, $user->password)) {
                return response()->json([
                    'success' => false,
                    'message' => '登录失败，密码错误或者账号错误',
                ], 401);
            }

            // 检查用户类型是否匹配
            if ($user->user_type !== $request->user_type) {
                return response()->json([
                    'success' => false,
                    'message' => '登录失败，密码错误或者账号错误',
                ], 401);
            }

            // 创建令牌
            $token = $user->createToken('auth-token')->plainTextToken;

            return response()->json([
                'success' => true,
                'message' => $request->user_type === 'admin' ? '管理员登录成功' : '登录成功',
                'data' => [
                    'user' => $user,
                    'token' => $token
                ]
            ], 200);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '登录失败，密码错误或者账号错误',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '登录失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 用户登出
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        try {
            $request->user()->currentAccessToken()->delete();

            return response()->json([
                'success' => true,
                'message' => '登出成功'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '登出失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取当前用户信息
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function user(Request $request)
    {
        return response()->json([
            'success' => true,
            'message' => '获取用户信息成功',
            'data' => $request->user()
        ], 200);
    }
}